package cgs_worksheet

import (
	"cgs-server/helper"
	"cgs-server/server"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"net/http"
	"strconv"
	"strings"
)

func init() {
	//server.Handle(http.MethodGet, "/api/Cgs/Worksheet/GetWorksheetInfo", GetWorksheetInfo, server.ListWorksheet)
	//server.Handle(http.MethodGet, "/api/Cgs/Worksheet/GetWorksheetDetail", GetWorksheetDetail, server.ListWorksheet)

	//server.Get("/api/Cgs/Worksheet/GetWorksheetInfo", GetWorksheetInfo, "获取表单列表", server.Login)
	server.Get("/api/Cgs/Worksheet/GetWorksheetDetail", GetWorksheetDetail, "获取表单详情", server.Login)
}

// 查询表格信息
func GetWorksheetInfo2(w http.ResponseWriter, r *http.Request) {

	// 权限验证
	/*if server.Config.Authority.Enabled {
		user, _ := server.GetCurrentUser(r)

		if user == nil {
			_, _ = helper.WriteJSON(w, server.CgsResult{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}

	}*/

	// 查询列表
	_ = r.ParseForm()

	// 分页
	//category, _ := strconv.ParseInt(r.FormValue("Category"), 10, 64)
	pageNo, _ := strconv.ParseInt(r.FormValue("pageNo"), 10, 64)
	pageSize, _ := strconv.ParseInt(r.FormValue("pageSize"), 10, 64)

	// 排序
	sortField := strings.TrimSpace(r.FormValue("sortField"))
	sortOrder := strings.TrimSpace(r.FormValue("sortOrder"))

	opts := options.FindOptions{
		Sort: bson.M{
			"updateTime": -1,
		},
	}

	if sortField != "" && sortOrder != "" {
		if sortOrder == "ascend" { // 升序
			opts.Sort = bson.M{
				sortField: 1,
			}
		} else {
			opts.Sort = bson.M{
				sortField: -1,
			}
		}
	}

	skip := int64(0)

	if pageNo > 0 {
		skip = (pageNo - 1) * pageSize
	} else {
		pageNo += 1
	}
	if pageSize == 0 {
		pageSize = 100
	}

	opts.Skip = &skip
	opts.Limit = &pageSize

	// 总页数
	count := int64(0)

	// 数据库连接
	db, err := server.Mongo()
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	// 这里需要一个数组接收
	var worksheetInfos []WorksheetInfo

	filter1 := bson.M{
		"$or": bson.A{
			bson.M{
				"isDeleted": 0,
			},
			bson.M{
				"isDeleted": nil,
			},
		},
	}

	if server.Config.Authority.Enabled {
		user, _ := server.GetCurrentUser(r)

		// 过滤条件
		// 管理员可以获取自己和没有用户 id 的表单信息
		if user != nil {
			if user.RoleName == "Administrator" {
				filter1 = bson.M{
					"$and": bson.A{
						filter1,
						bson.M{
							"$or": bson.A{
								bson.M{
									"userId": user.ID,
								},
								bson.M{
									"userId": bson.M{
										"$exists": 0,
									},
								},
							},
						},
					},
				}
			} else {
				filter1["userId"] = user.ID
			}
		}
	}

	count, _ = db.Count(server.CgsWorksheetInfoCollectionName, filter1)
	_ = db.FindMany(server.CgsWorksheetInfoCollectionName, filter1, &worksheetInfos, &opts)

	result := server.PageResult{
		CgsResult: server.CgsResult{
			Code: 200,
			Msg:  "Get Successfully!",
			Data: worksheetInfos,
		},
		PageNo:     pageNo,
		PageSize:   pageSize,
		TotalCount: count,
	}
	result.CalculateTotalPage()

	_, _ = helper.WriteJSON(w, result)

}

// 单个表单信息
func GetWorksheetDetail(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseForm()

	id, err := primitive.ObjectIDFromHex(strings.TrimSpace(r.FormValue("id")))
	if err != nil {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "NodeId is not allowed empty.",
		})
		return
	}

	filter := bson.M{
		"id": id,
	}

	var worksheetInfo WorksheetInfo

	// 数据库连接
	db, err := server.Mongo()
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	find, _ := db.FindOne(server.CgsWorksheetInfoCollectionName, filter, &worksheetInfo)
	if !find {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Worksheet is not exist.",
		})
		return
	}

	_, _ = helper.WriteJSON(w, server.CgsResult{
		Code: 200,
		Msg:  "Get Successfully!",
		Data: worksheetInfo,
	})
}
